﻿@page "/Account/Login"

@using HtERP.Components.Layout
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Server
@using System.Security.Claims
@using SqlSugar;
@using HtERP.Data
@using System.Security.Cryptography
@using System.Text
@inject AuthenticationStateProvider AuthStateProvider
@inject NavigationManager NavigationManager
@inject Blazored.LocalStorage.ILocalStorageService localStorage

<PageTitle>Log in</PageTitle>

<h1>登录</h1>
<div class="row">
    <div class="col-md-4">

                <p>
            <h2 style="color: #AA0000;">@logz</h2>
                </p>
                <h3>使用手机号登录</h3>
                <hr />
               
                <div class="form-floating mb-3">
                <InputText @bind-Value=@Phone class="form-control" autocomplete="username" aria-required="true" placeholder="username" />
                 <label for="username" class="form-label">手机号</label>
                    
                </div>
                <div class="form-floating mb-3">
                <InputText type="password" @bind-Value="@Password" class="form-control" autocomplete="current-password" aria-required="true" placeholder="password" />
                    <label for="password" class="form-label">密码</label>
                    
                </div>
     
                <div>
                <button @onclick="@SignIn" class="w-100 btn btn-lg btn-primary">确 定</button>
           
                </div>
                <div>
                    <p>
                        <a href="Account/ForgotPassword">忘记密码?</a>
                    </p>
               
                </div>
           
        
    </div>

</div>


@code {
    string logz = "";
    string Phone = "";
    string Password = "";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        string pwd = Convert.ToHexString(MD5.HashData(Encoding.UTF8.GetBytes(Password)));
        if (firstRender)
        {
            if (await localStorage.ContainKeyAsync("Phone"))
            {
                //读取登录状态，因为是Demo所以直接存储用户名，实际项目中应该是一个加密数据或者随机标识符
                Phone = await localStorage.GetItemAsync<string>("Phone");
                pwd = await localStorage.GetItemAsync<string>("Password");

                await InvokeAsync(StateHasChanged);

                //身份验证
                if (HongtengDbCon.Db.Queryable<员工>().Any(it => it.手机 == Phone && it.密码 == pwd && it.是否已离职 != true))
                { await BuildingIdentity(Phone, pwd); }
            }
        }
    }

    private async void SignIn()
    {
        //验证账号密码
        //身份验证
        //构建身份
        if (Phone != "" & Password != "")
        {

            string pwd = Convert.ToHexString(MD5.HashData(Encoding.UTF8.GetBytes(Password))).ToLower();
            //验证账号密码
            if (HongtengDbCon.Db.Queryable<员工>().Any(it => it.手机 == Phone && it.密码 == pwd ))
            {
                bool? depart = HongtengDbCon.Db.Queryable<员工>().First(it => it.手机 == Phone).是否已离职;
                if (depart != true)
                {
                    //构建身份
                    await BuildingIdentity(Phone, pwd);
                }
                logz = "您已离职，不能再登录系统";

            }
            else
            {
                
                logz = "用户名或密码错误，请重新登陆";
            }
        }
        else
        {
            logz = "用户名密码不能为空!";
        }

        await InvokeAsync(StateHasChanged);
    }

    //构建身份
    public async Task BuildingIdentity(string Phone, string Password)
    {
        var yuangong = HongtengDbCon.Db.Queryable<员工>().First(it => it.手机 == Phone && it.密码 == Password && it.是否已离职 != true);
        string? nime = yuangong.姓名;
        var identity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, nime),
                new Claim("UPMaster", "员工"),
            }, "Custom Authentication");
        var user = new ClaimsPrincipal(identity);

        AuthenticationState state = new AuthState(user)
            {
                IsLike = true,
                Coining = 2,
                Phone = Phone,
                UserName = nime,
                BuMen = yuangong.部门,
                IsAdmin = yuangong.是否为管理员,
                IsAdminPro = yuangong.超级管理员,
            };

        var authStateProvider = (ServerAuthenticationStateProvider)AuthStateProvider;

        var ss = await authStateProvider.GetAuthenticationStateAsync();
        authStateProvider.SetAuthenticationState(Task.FromResult(state));

        //用户名写入存储
        await localStorage.SetItemAsStringAsync("UserName", nime);
        await localStorage.SetItemAsStringAsync("Phone", Phone);
        await localStorage.SetItemAsStringAsync("Password", Password);

        var uri = new Uri(NavigationManager.Uri);
        var ReturnUrl = System.Web.HttpUtility.ParseQueryString(uri.Query)["ReturnUrl"];
        NavigationManager.NavigateTo(string.IsNullOrWhiteSpace(ReturnUrl) ? "/" : ReturnUrl);
    }
}